package topic

import (
	"community-service/cmd/api/internal/models/model"
	"community-service/cmd/api/internal/svc"
	"community-service/cmd/api/internal/types"
	e "community-service/pkg/errorx"
	"context"
	"google.golang.org/grpc/codes"
	"gorm.io/gorm"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateTopicLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUpdateTopicLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateTopicLogic {
	return &UpdateTopicLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UpdateTopicLogic) UpdateTopic(req *types.TopicUpdateReq) (resp *types.Empty, err error) {

	topicQuery := l.svcCtx.DB.WithContext(l.ctx).Model(&model.CsCommunityTopic{})

	// 检查话题是否存在
	var existTopic model.CsCommunityTopic
	if err = topicQuery.Session(&gorm.Session{}).Where("id = ?", req.Id).Find(&existTopic).Error; err != nil {
		return nil, e.NewGrpcErr(codes.Internal, e.DBError)
	}

	if existTopic.ID == 0 {
		return nil, e.NewGrpcErr(codes.NotFound, e.TopicNotFound)
	}

	// 检查名称是否重复（排除自己）
	if req.Name != "" {
		var duplicateTopic model.CsCommunityTopic
		if err = topicQuery.Session(&gorm.Session{}).Where("name = ? AND menu_id = ? AND id != ?", req.Name, existTopic.MenuID, req.Id).Find(&duplicateTopic).Error; err != nil {
			return nil, e.NewGrpcErr(codes.Internal, e.DBError)
		}

		if duplicateTopic.ID != 0 {
			return nil, e.NewGrpcErr(codes.AlreadyExists, e.TopicNameEmpty) // 可以添加专门的话题名称重复错误码
		}
	}

	if err = topicQuery.Where("id = ?", req.Id).
		Select("name", "image_url", "description", "type").
		Updates(&model.CsCommunityTopic{
			Name:        req.Name,
			ImageURL:    req.ImageUrl,
			Description: req.Description,
			Type:        req.Type,
		}).Error; err != nil {
		return nil, e.NewGrpcErr(codes.Internal, e.DBError)
	}

	return &types.Empty{}, nil
}
